<template>
  <ContentWrap>
    <div class="container-card" v-loading="loading" element-loading-text="努力加载中...">
      <el-card  class="card-list" style="background-color:#3699FF">
        <el-row :gutter="20">
          <el-col :span="24" class="list-item-weather">
            <div class="list-item-top">
              <div class="top-weather">
                <div class="top-temp"> {{weatherList.degree}} ℃</div>
                <div class="top-condition">{{weatherList.weather }}</div>
              </div>
                <div>
                    <img src ="@/assets/imgs/iot/weather.png" />
                </div>
            </div>

            <div class="list-item-middle">
              <div class="middle-weather">
                <div class="middle-humi">
                  <div>
                     <img src ="@/assets/imgs/iot/humi.png" />
                  </div>
                  <text>{{weatherList.humidity}} %</text>
                </div>
                <div class="middle-humi">
                  <div>
                     <img src ="@/assets/imgs/iot/wind.png" />
                  </div>
                  <text>{{weatherList.wind_power}} 级</text>
                </div>
                <div class="middle-humi">
                  <div>
                     <img src ="@/assets/imgs/iot/Pa.png" />
                  </div>
                  <text>{{weatherList.pressure}} Pa</text>
                </div>
                <div class="middle-humi">
                  <div>
                     <img src ="@/assets/imgs/iot/PM2.5.png" />
                  </div>
                  <text>{{weatherList.wind_direction_name}}</text>
                </div>
              </div>
            </div>
            <div class="list-item-bottom">
              <el-tree-select
                v-model="queryParams.farmHouseId"
                :data="deptList"
                :render-after-expand="false"
                placeholder="请选择农舍"
                @change="hangdleChange"
              />
            </div>
          </el-col>
        </el-row>
      </el-card> 

      <el-card  class="card-list" style="background-color:#FFB822">
        <el-row :gutter="20">
          <el-col :span="24" class="list-item">
            <div class="item-device-left" >
              <div class="device-box-status">
                <div class="status">实时告警</div>
                <div class="status-persent1">设备异常告警{{alarm}} 个</div>
              </div>
            </div>
            <div class="item-device-right">
               <Icon icon="ep:warning" :size="33" class="mr-5px" />
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card  class="card-list" style="background-color:#1BC5BD">
        <el-row :gutter="20">
          <el-col :span="24" class="list-item">
            <div class="item-device-left" >
              <div class="device-box-status">
                <div class="status">今日产蛋</div>
                <div class="status-persent">{{eggNUmber !== null ? eggNUmber : '-'}}  枚</div>
              </div>
              <!-- <div class="device-num">环比增长:{{number}} %</div> -->
            </div>
            <div class="item-device-right">
               <Icon icon="ep:flag" :size="33" class="mr-5px" />
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card  class="card-list" style="background-color:#8950FC">
        <el-row :gutter="20">
          <el-col :span="24" class="list-item">
            <div class="item-device-left" >
              <div class="device-box-status">
                <div class="status">设备运行状态</div>
                <div class="status-persent">{{deviceStatus}}%</div>
              </div>
              <div class="device-num">正常运行设备:{{number}} 台</div>
            </div>
            <div class="item-device-right">
               <Icon icon="ep:monitor" :size="33" class="mr-5px" />
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </ContentWrap>

  <ContentWrap>
    <div class="container-info" v-loading="loading" element-loading-text="努力加载中...">
      <el-card  class="card-list">
        <h4>基础信息</h4>
        <el-row :gutter="20" class="card-list-first">
          <el-col :span="8" class="list-item">
            <div class="item-first">
              <span style="color:#2587e9;">{{day}}</span>
              <span style="margin-top:10px">日龄</span>
            </div>
          </el-col>
          <el-col :span="8" class="list-item">
            <div class="item-first">
              <span style="color:#2587e9;">{{remain}}</span>
              <span style="margin-top:10px">存栏</span>
            </div>
          </el-col>
           <el-col :span="8" class="list-item">
            <img :src="sweet"/>
          </el-col>
        </el-row>
      </el-card>

      <el-card  class="card-list">
        <h4>环境信息</h4>
        <el-row :gutter="20">
          <el-col :span="12" class="list-item">
            <div class="item-first">
              <span style="color:green">{{interTemperature}}/{{stemperature}}</span>
              <span>平均/目标温度</span>
            </div>
          </el-col>
          <el-col :span="12" class="list-item">
            <div class="item-first">
              <span style="color:green">{{airHumidity}}</span>
              <span>平均湿度</span>
            </div>
          </el-col>
        </el-row>
        <template #footer>
          <div class="list-temp">
            <div class="temp">
              <span>通风级别(Lv):</span>
              <span style="color:green">{{pulseWindLevel}} Lv</span>
            </div>
            <div class="temp">
              <span>脉冲风速(%):</span>
              <span style="color:green">{{pulseWindSpeed}} %</span>
            </div>
            <div class="temp">
              <span>NH3浓度(ppm):</span>
              <span style="color:green">{{nh3Concentration}} ppm</span>
            </div>
            <div class="temp">
              <span>co2浓度(ppm):</span>
              <span style="color:green">{{co2Concentration}} ppm</span>
            </div>
            <div class="temp">
              <span>室内压强(Pa):</span>
              <span style="color:green">{{interPressure}} Pa</span>
            </div>
          </div>
        </template>
      </el-card>

      <el-card class="card-list">
        <h4>设备运行</h4>
        <el-carousel height="300px">
          <el-carousel-item>
            <el-row :gutter="10">
              <el-col v-for="(item, index) in windDevicesList" :key="index" :span="6" class="device-item">
                <div class="device">
                  <div class="device-info">
                    <div class="info-img">
                        <img :src="item.imageUrl" class="device-img" :class="(item.status == 0 ?'gray-image': '')+(item.status ==1 && item.text.indexOf('风机') !== -1?'rotateImg':'') + ' image'" />
                        <div>{{ item.text }}</div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-carousel-item>
          <el-carousel-item v-if="other.length > 0">
            <el-row :gutter="10">
              <el-col v-for="(item, index) in other" :key="index" :span="6" class="device-item">
                <div class="device">
                  <div class="device-info">
                    <div class="info-img">
                       <img :src="item.imageUrl" class="device-img" :class="(item.status == 0 ?'gray-image':'')+(item.status ==1 && item.text.indexOf('通风窗') !== -1 ? ' ' :'') + ' image'" />
                        <div>{{ item.value }} %</div>
                        <div>{{ item.text }}</div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-carousel-item>
          <el-carousel-item v-else>暂无数据</el-carousel-item>
        </el-carousel>
      </el-card>
    </div>
  </ContentWrap>

  <ContentWrap>
    <div class="sort" v-loading="loading" element-loading-text="努力加载中...">
      <h2>近24H数据曲线</h2>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="温度" name="first" :lazy="true">
          <div>
            <div ref="tempChartRef" style="height: 400px; width: 100%;"></div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="湿度" name="second" :lazy="true">
          <div>
            <div ref="humidityChartRef" style="height: 400px; width: 100%;"></div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="CO2" name="third" :lazy="true">
          <div>
            <div ref="co2ChartRef" style="height: 400px; width: 100%;"></div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </ContentWrap>

  <ContentWrap>
    <div class="sort" v-loading="loading" element-loading-text="努力加载中...">
      <h2>消耗数据</h2>
      <div style="margin-bottom: 20px">
        <WaterCharts :data="waterChartData"/>
      </div>
      <div style="margin-top: 20px">
        <FoodCharts :data="foodChartData"/>
      </div>
      <div style="margin-top: 20px">
        <ElectricityCharts :data="ElectricityChartData"/>
      </div>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref,watch,nextTick} from 'vue';
import { useI18n } from 'vue-i18n';
import { debounce } from 'lodash';
import { FarmTourApi,FarmTourVO } from '@/api/farmTour/index';
import {farmHouseExpend} from '@/api/houseTour/houseOverview/index';
import { tr } from 'node_modules/element-plus/es/locale';
import WaterCharts from '@/views/houseTour/component/WaterCharts.vue';
import FoodCharts from "@/views/houseTour/component/FoodCharts.vue"
import Echarts24h from "@/views/houseTour/component/Echarts24h.vue"
import { getLast7Days } from '@/utils/formatTime';
import { FarmWarnApi, FarmWarnApiVO } from '@/api/farmTour/warn/index';
import type { TabsPaneContext } from 'element-plus';
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as echarts from "echarts";
import sweet from "@/assets/imgs/iot/sweet.png";
import windLogo  from "@/assets/imgs/iot/风机组_on.png";
import warnLogo from "@/assets/imgs/iot/报警.png";
import penwuLogo from "@/assets/imgs/iot/喷雾.png";
import shuibeng from "@/assets/imgs/iot/水泵.png";
import windows from "@/assets/imgs/iot/通风窗.png";
import light from "@/assets/imgs/iot/光照.png";
import { string } from 'vue-types';
  defineOptions({ name: 'HouseOverview' })
  const { t } = useI18n();
  const loading = ref(true) // 列表的加载中

  const deptList = ref([]); // 用于存储农舍列表

  const farmTourValue = ref<any>('')
  const farmTourList = ref<FarmTourVO[]>([])
  const eggNUmber = ref<number>(0)
  const alarm = ref<any>('-')//实时告警数量
  const deviceStatus = ref<any>('-')//运行状态占比
  const number = ref<any>('-')//设备总数
  const interTemperature = ref(0)//平均温度
  const stemperature = ref(0)//目标温度
  const airHumidity = ref(0)//平均湿度
  const remain = ref(0)//存栏
  const pulseWindLevel = ref(0)//通风级别
  const pulseWindSpeed = ref(0)//脉冲风速
  const nh3Concentration = ref(0)//NH3浓度
  const co2Concentration = ref(0)//co2浓度
  const interPressure = ref(0)//室内压强
  const windDevicesList = ref<WindDevice[]>([
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组1'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组2'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组3'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组4'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组5'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组6'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组7'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组8'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组9'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '风机组10'
		},
    {
			imageUrl: shuibeng,
			status: 0,
			text: '水泵'
		},
    {
			imageUrl: penwuLogo,
			status: 0,
			text: '喷雾'
		},
    {
			imageUrl: windLogo,
			status: 0,
			text: '警报'
		},
  ]); // 用于存储风机数据
  const other=ref<otherVO[]>([
		{
      imageUrl: windows,
      status: 0,
			value: '-',
			text: '侧墙通风窗1'
		}, 
   	{
      imageUrl: windows,
      status: 0,
			value: '-',
			text: '侧墙通风窗2'
		},  
    		{
      imageUrl: windows,
      status: 0,
			value: '-',
			text: '侧墙通风窗3'
		}, 
   		{
      imageUrl: windows,
      status: 0,
			value: '-',
			text: '侧墙通风窗4'
		}, 
    {
      imageUrl: windows,
      status: 0,
			value: '-',
			text: '湿帘挡风板2'
		},  
    {
      imageUrl: windows,
      status: 0,
			value: '-',
			text: '屋顶通风窗'
		}, 
    {
      imageUrl: light,
      status: 0,
			value: '-',
			text: '光照亮度'
		},
	])  
  const farmId = ref<number>(0)
  const houseList = ref<any[]>([]); // 存储农舍列表 
  const weatherList = ref([])//天气
  const day = ref<number>(0)
  const monitorList = ref([])

  const totalWeight = ref(0); // 总耗料
  const totalWater = ref(0); // 总耗水
  const avgWeight = ref(0); // 平均耗料
  const avgWater = ref(0); // 平均耗水
  const waterChartData  = ref([]); // 传递给水图表
  const foodChartData = ref([]); // 传递给食物图表
  const ElectricityChartData = ref([]);//耗电量

  const total = ref(0) // 列表的总页数
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 10,
    farmId:undefined,
    farmHouseName:undefined,
    farmHouseId:undefined,
    startTime:undefined,
    timeRange:[],
  })
const activeName = ref('first')
const handleClick =async  (tab: TabsPaneContext, event: Event) => {
  console.log(tab.props.name, 'name')
  await nextTick();
  if (tab.props.name === 'first') {
    await hosueData24hApi(queryParams.farmHouseId); // 获取数据并绘制温度图
  } else if (tab.props.name === 'second') {
    await hosueData24hApi(queryParams.farmHouseId); // 获取数据并绘制湿度图
  } else if (tab.props.name === 'third') {
    await hosueData24hApi(queryParams.farmHouseId); // 获取数据并绘制 CO2 图
  }
}

// 图表引用
const tempChartRef = ref<any>(null);
const humidityChartRef = ref<any>(null);
const co2ChartRef = ref<any>(null);
const ventilationChartRef = ref<any>(null);




// ts 
interface WindDevice {//风机组
  imageUrl: string;
  status: any;
  text: string;
}
interface otherVO {//风机组
  imageUrl: string;
  status: any;
  value:any;
  text: string;
}

const getHouseList = async () => {
  loading.value = true;
  try {
    const res = await farmHouseExpend.getHouseListApi();
    console.log(res, 'res农舍列表');
    if (res) {
      deptList.value = res.map(item => ({
        value: item.id,
        label: item.name,
        children: item.children ? item.children.map(child => ({
          value: child.id,
          label: child.name,
        })) : []
      }));
      // 设置默认选择，选择第一个农舍的第一个子项
      if (deptList.value.length > 0 && deptList.value[0].children.length > 0) {
        queryParams.farmHouseId = deptList.value[0].children[0].value;
        await fetchDataForSelectedHouse(queryParams.farmHouseId);
        await fetchWeatherData(queryParams.farmHouseId);
      }
    }else{
      deptList.value = []
    }
  } catch (error) {
    console.error('请求失败:', error);
  }finally{
    loading.value = false;
  }
};
// 方法：切换农舍时调用
const hangdleChange = async (selectedHouseId) => {
  await fetchDataForSelectedHouse(selectedHouseId); // 根据选择的农舍获取数据
};
// 方法：获取相关数据
const fetchDataForSelectedHouse = async (farmHouseId) => {
  getEgg(farmHouseId);
  fetchWeatherData(farmHouseId);//天气
  getStatus(farmHouseId);
  baseInfo(farmHouseId);
  windDevice(farmHouseId);
  getNowWarn(farmHouseId);
  getWaterData(farmHouseId);//耗水
  getFoodData(farmHouseId);//耗料
  getEletricityData(farmHouseId);//耗电
  hosueData24hApi(farmHouseId);
};

//天气信息
const fetchWeatherData = async (farmHouseId) => {
  const params = {
    farmHouseId: queryParams.farmHouseId
  };
  try {
    const res = await farmHouseExpend.getHouseWeather(params)
    console.log(res.data.observe,'res天气预报')
    weatherList.value = res.data.observe
  } catch (error) {
    ElMessage.error('获取天气数据失败');
    console.error(error);
    weatherList.value = []
  } finally {
  }
};

// 今日产蛋
const getEgg = async (farmHouseId) => {
  const params = {
      farmHouseId: queryParams.farmHouseId
  };
  try {
      const res = await farmHouseExpend.getEggNumApi(params);
      if (res&& res.length > 0) {
          eggNUmber.value = res[0].num;  // 提取产蛋数量
          console.log(eggNUmber.value, '今日产蛋数量');
      } else {
          eggNUmber.value = 0;
      }
  } catch (error) {
      console.error('获取今日产蛋数据时出错:', error);
  }
};
// 设别运行状态
const getStatus =async (farmHouseId) => {
    const params = {
    farmHouseId: queryParams.farmHouseId
  };
  try {
      const res = await farmHouseExpend.getHouseWarn(params);
      if (res&& res.length > 0) {
        number.value = res.total;
        deviceStatus.value = res.normal / res.total * 100;
        alarm.value = res.alarm;
      } else {
        number.value = '-';
        deviceStatus.value = '-';
        alarm.value = '-';
      }
  } catch (error) {
    number.value = '-';
    deviceStatus.value = '-';
    alarm.value = '-';
  }
}

//实时告警
const getNowWarn = async (farmHouseId) => {
  const params = {
    farmHouseId: queryParams.farmHouseId
  };
  console.log();
  
  const res = await farmHouseExpend.getNowHouseWarnApi(params)
  if (res) {
    console.log(res,'resgetNowWarn')
    alarm.value = res;
  }
}

//基础信息
const baseInfo = async(farmHouseId)=>{
  loading.value = true
  const params = {
    farmHouseId:queryParams.farmHouseId,
  };
  const res = await farmHouseExpend.getBaseInfoApi(params);
  try{
    if (res) {
      console.log(res,'基础信息');
      day.value = res.grows;//日龄
      interTemperature.value = res.interTemperature;//平均温度
      airHumidity.value = res.airHumidity;//平均湿度
      remain.value = res.remain
      pulseWindLevel.value = res.pulseWindLevel//通风级别
      pulseWindSpeed.value = res.pulseWindSpeed//脉冲风速
      nh3Concentration.value = res.nh3Concentration//NH3浓度
      co2Concentration.value =res.co2Concentration//co2浓度
      interPressure.value = res.interPressure//室内压强
    }
  }catch{

  }finally{
    loading.value = false
  }
}

// 风机
const windDevice = async(farmHouseId)=>{
  loading.value = true
  const params = {
    farmHouseId:queryParams.farmHouseId,
  };
  const res = await farmHouseExpend.getWindApi(params);
  try{
    if (res) {
      console.log(res.main,'风机信息');
      console.log(res.other,'风机其他信息');
      windDevicesList.value =[
        {
          imageUrl: windLogo ,
          status: `${res.main.fan1 !== null ? res.main.fan1 : 0}`,
          text: '风机组1'
        },
        {
          imageUrl: windLogo,
          status: `${res.main.fan2 !== null ? res.main.fan2 : 0}`,
          text: '风机组2'
        },
        {
          imageUrl: windLogo,
          status: `${res.main.fan3 !== null ? res.main.fan3 : 0}`,
          text: '风机组3'
        },
        {
          imageUrl: windLogo,
          status: `${res.main.fan4 !== null ? res.main.fan4 : 0}`,
          text: '风机组4'
        },
        {
          imageUrl: windLogo,
          status: `${res.main.fan5 !== null ? res.main.fan5 : 0}`,
          text: '风机组5'
        },
        {
          imageUrl: windLogo,
          status: `${res.main.fan6 !== null ? res.main.fan6 : 0}`,
          text: '风机组6'
        },
        {
          imageUrl: windLogo,
          status: `${res.main.fan7 !== null ? res.main.fan7 : 0}`,
          text: '风机组7'
        },
        {
          imageUrl: windLogo,
          status: `${res.main.fan8 !== null ? res.main.fan8 : 0}`,
          text: '风机组8'
        },
        {
          imageUrl: windLogo,
          status: `${res.main.fan9 !== null ? res.main.fan9 : 0}`,
          text: '风机组9'
        },
        {
          imageUrl: shuibeng,
          status: `${res.main.water !== null ? res.main.water : 0}`,
          text: '水泵'
        },
        {
          imageUrl: penwuLogo,
          status:`${res.main.spray !== null ? res.main.spray : 0}`,
          text: '喷雾'
        },
        {
          imageUrl: warnLogo,
          status: `${res.main.alarm !== null ? res.main.alarm : 0}`,
          text: '警报'
        },
      ];
      other.value=[
        {
          imageUrl: windows,
          status: `${res.other.sideWindow_1 !== null ? 1 : 0}`,
          value: `${res.other.sideWindow_1 !== null ? res.other.sideWindow_1 : '-'}`,
          text: '侧墙通风窗1'
        }, 
        {
          imageUrl: windows,
          status: `${res.other.sideWindow_2 !== null ? 1 : 0}`,
          value: `${res.other.sideWindow_2 !== null ? res.other.sideWindow_2 : '-'}`,
          text: '侧墙通风窗2'
        }, 
        {
          imageUrl: windows,
          status: `${res.other.sideWindow_3 !== null ? 1 : 0}`,
          value: `${res.other.sideWindow_3 !== null ? res.other.sideWindow_3 : '-'}`,
          text: '侧墙通风窗3'
        }, 
        {
          imageUrl: windows,
          status: `${res.other.windshield_1 !== null ?1 : 0}`,
          value: `${res.other.windshield_1 !== null ? res.other.windshield_1 : '-'}`,
          text: '湿帘挡风板1'
        }, 
        {
          imageUrl: windows,
          status: `${res.other.windshield_2 !== null ? 1 : 0}`,
          value: `${res.other.windshield_2 !== null ? res.other.windshield_2 : '-'}`,
          text: '湿帘挡风板2'
        }, 
        {
          imageUrl: windows,
          status: `${res.other.dormer !== null ?1 : 0}`,
          value: `${res.other.dormer !== null ? res.other.dormer : '-'}`,
          text: '屋顶通风窗'
        }, 
        {
          imageUrl: light,
          status: `${res.other.brightness !== null ? 1 : 0}`,
          value: `${res.other.brightness !== null ? res.other.brightness : '-'}`,
          text: '光照亮度'
        }, 
      ]  
    }
  }catch{

  }finally{
    loading.value = false
  }
}


// 获取耗水数据
const getWaterData = async (farmHouseId:any) => {
  loading.value = true;
  const [startTime, endTime] = getLast7Days();
  const params = {
    farmHouseId: queryParams.farmHouseId,
    createTime: [startTime, endTime]
  };
  try {
    const res = await farmHouseExpend.getTodayWaterApi(params);
    console.log(res,'res耗水');
    if (res ) {
      // 处理图表数据
      const chartData = res.map(item => ({
        createTime: new Date(item.createTime).toLocaleString(), // 转换为可读时间
        waterConsumption: item.waterConsumption,
      }));
      waterChartData.value = chartData; // 传递耗水
    } else {
      // 处理错误信息
      console.error('API错误:', res.msg);
    }
  } catch (error) {
    console.error('获取数据时出错:', error);
  } finally {
    loading.value = false;
  }
};
// 耗料数据
const getFoodData = async (farmHouseId:any) => {
  loading.value = true;
  const [startTime, endTime] = getLast7Days();
  const params = {
    farmHouseId: queryParams.farmHouseId,
    createTime: [startTime, endTime]
  };
  try {
    const res = await farmHouseExpend.getTodayConsumeApi(params);
    if (res ) {
      // 处理图表数据
      const chartData = res.map(item => ({
        createTime: new Date(item.createTime).toLocaleString(), // 转换为可读时间
        todayUse: item.todayUse,
      }));
      foodChartData.value = chartData; // 传递给耗料
    } else {
      // 处理错误信息
      console.error('API错误:', res.msg);
    }
  } catch (error) {
    console.error('获取数据时出错:', error);
  } finally {
    loading.value = false;
  }
};
// 耗电数据
const getEletricityData = async (farmHouseId:any) => {
  loading.value = true;
  const [startTime, endTime] = getLast7Days();
  const params = {
    farmHouseId: queryParams.farmHouseId,
    createTime: [startTime, endTime]
  };
  try {
    const res = await farmHouseExpend.getTodayElectricityApi(params);
    // console.log(res,'res耗电');
    if (res ) {
      // 处理图表数据
      const chartData = res.map(item => ({
        createTime: new Date(item.createTime).toLocaleString(), // 转换为可读时间
        meter: item.active,
      }));
      ElectricityChartData.value = chartData; // 传递给耗料
    } else {
      // 处理错误信息
      console.error('API错误:', res.msg);
    }
  } catch (error) {
    console.error('获取数据时出错:', error);
  } finally {
    loading.value = false;
  }
};

// 近24小时数曲线
const hosueData24hApi = async (farmHouseId) => {
  console.log(farmHouseId,'farmHouseId')
  const params = {
    farmHouseId:queryParams.farmHouseId,
  };
  try {
    const res = await farmHouseExpend.getHosueData24hApi(params)
    console.log(res,'res24小时')
    const timeData: string[] = [];
    const innerTempData: number[] = [];
    const outerTempData: number[] = [];
    const humidityData: number[] = [];
    const co2Data: number[] = [];
    const innerPresData: number[] = [];
    const setTempData: number[] = [];
    res.forEach((
      data: { 
        createTime: number; 
        innerTemp: number; 
        outerTemp: number; 
        innerHumi: number; 
        innerCo2: number; 
        innerPres: number;
        setTemp:number
      }) => {
      timeData.push(new Date(data.createTime).toLocaleString());
      innerTempData.push(data.innerTemp);
      outerTempData.push(data.outerTemp);
      humidityData.push(data.innerHumi);
      co2Data.push(data.innerCo2);
      innerPresData.push(data.innerPres);
      setTempData.push(data.setTemp);
    });

    drawChart(tempChartRef.value, '温度(℃)', ['内部温度', '外部温度','负压','目标温度'], [innerTempData, outerTempData,innerPresData,setTempData], timeData);
    drawChart(humidityChartRef.value, '湿度(%)', ['湿度'], [humidityData], timeData);
    drawChart(co2ChartRef.value, '二氧化碳(ppm)', ['二氧化碳浓度'], [co2Data], timeData);
  } catch (error) {
    console.error('请求数据时出错:', error);
  }finally{
    loading.value = false;
  }
}

const drawChart = (chartRef, title, legendData, seriesDataList, xAxisData) => {
  loading.value = true;
  // 绘制图表
  if (!chartRef) {
    console.error('chartRef is not available');
    return;
  }
  try {
    const myChart = echarts.init(chartRef);
    const series = legendData.map((name, index) => ({
      name,
      type: 'line',
      smooth: true,
      data: seriesDataList[index] || [],
      symbolSize: 1,
    }));

    const options = {
      title: { text: title },
      tooltip: { trigger: 'axis' },
      legend: { data: legendData },
      toolbox: {
        show: true,
        feature: {
          // dataZoom: {},
          // dataView: {readOnly: false},
          magicType: {type: ['line', 'bar','pie']},
          restore: {},
          // saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xAxisData || [],
      },
      yAxis: { type: 'value' },
      series: series,
      dataZoom: [
        {
          type: 'slider',
          start: 0,
          end: 100,
        },
        {
          type: 'inside',
        }
      ],
      // 添加高亮效果
      markPoint: {
        data: [
          {
            type: 'max',
            name: '最大值',
            // 这里可以设置具体高亮的点
            valueIndex: 0, // 或者根据 seriesIndex 选择
          }
        ],
      }
    };

    myChart.setOption(options);
    window.addEventListener('resize', () => {
      myChart.resize();
    });
  }catch{
    console.error('绘制图表时出错:', error);
  }finally{
    loading.value = false;
  }

};

// 监听切换温度，湿度，二氧化碳曲线
const onFarmHouseChange = async (selectedHouseId) => {
  loading.value = true
  // 调用获取24小时数据
  await hosueData24hApi(selectedHouseId);
  // 调用获取消耗数据
  await getHouseExpendData(selectedHouseId);
  loading.value = false
};

onMounted( () => {
  getHouseList()
})
</script>

<style scoped lang="scss">
  h2{
    margin: 10px;
  }
  .el-carousel__item:nth-child(2n) {
    background-color: hsl(201, 79%, 54%);
  }

  .el-carousel__item:nth-child(2n + 1) {
    background-color:#5de3e3;
  }
  .container-card {
    display: flex;
    justify-content: space-between;
    .card-list {
      border-radius: 8px;
      flex: 1 1 calc(25% - 10px);
      margin: 10px;
      color: #ffffff;
      // 天气
      .list-item-weather{
        .list-item-top{
          display: flex;
          flex-direction: row;
          padding: 8px;
          justify-content: space-between;
          .top-weather{
            display: flex;
            justify-content: space-around;
            .top-temp{
              margin-right: 5px;
              font-size: 22PX;
              font-weight: bold;
            }
            .top-condition{
              margin-left: 5px;
            }
          }
          img{
            width: 2.5rem;
            height: 2.5rem;
          }
        }
        .middle-weather{
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          .middle-humi{
            flex: 1 1 calc(50% - 8px);
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            img{
              width: 1.5rem;
              height: 1.5rem;
            }
            text{
              margin-left: 6px;
              font-size: 20px;
              font-weight: bold;
            }
          }
        }
      }

      // 告警、设备运行、产量
      .list-item{
        color: #ffffff;
        font-size: 20px;
        padding: 0px 10px;
        display: flex;
        justify-content:space-between;
        .item-device-left{
          .device-box-status{
            display: block;
            .status{
              margin: 10px 0px;
            }
            .status-persent{
              font-size: 26px;
              font-weight: bold;
            }
          }
        }
        .item-device-right{
          padding: 10px 0px;

        }
      }
    }
  }
  .container-info {
    display: flex;
    justify-content: space-between;
    .card-list {
      border-radius: 8px;
      flex: 1 1 calc(30% - 10px);
      margin: 10px;
      .el-carousel__item:nth-child(2n) {
        background-color: #ffffff;
      }

      .el-carousel__item:nth-child(2n + 1) {
        background-color: #ffffff;
      }
      .card-list-first{
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26px;
      }
      .list-item{
        padding: 10px;
        img{
          width: 100px;
        }
        .item-first{
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          text-align: center;
          
        }
      }

      .list-temp{
        display: flex;
        flex: 1 1 calc(30% - 10px);
        flex-wrap: wrap;
        .temp{
          margin: 10px;
        }
      }

      // 风机
      .device-item {
        display: flex;
        align-items: center; /* 垂直居中对齐 */
      }

      .device {
        display: flex;
        align-items: center; /* 垂直居中对齐 */
      }

      .device-icon {
        width: 40px; /* 图标大小调整 */
        height: 40px;
        margin-right: 10px; /* 图标与文本之间的间距 */
      }

      .device-info {
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        margin: 10px;
        .info-img{
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          text-align: center;
        }
        .gray-image {
          filter: grayscale(100%);
          /* 设置灰度值 */
        }
        .rotateImg{
          animation: rotate 2s linear infinite;
        }
        .device-img{
          width: 40px;
          height: 40px;
        }
      }

      .device-name {
        font-weight: bold;
        color: #333; /* 名称颜色 */
      }

      .device-status {
        color: #666; /* 状态颜色 */
      }
            
    }
  }

</style>
